package com.syygl.test.study.springTest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.commons.util.InetUtils;

import java.util.Collections;
import java.util.List;

public class getEurekaMicoServiceIP {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private InetUtils inetUtils;

    //判断是否是第一个容器
    public boolean isFirstMicoService(){
        //获取微服务所有的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("micoService name");
        if(null != instances && instances.size()>0){
            //对实例进行排序，保证每个实例获取的第一个都是同样的实例
            Collections.sort(instances, (o1, o2) ->{
                return o1.getHost().compareTo(o2.getHost());
            });
            //获取当前实例的IP地址
            String ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
            //IP地址一样的获得执行权
            if(instances.get(0).getHost().equals(ipAddress)){
                return true;
            }
        }
        return false;
    }
}
